const strategies = {
    isNonEmpty(value, errorMsg) {
        if (value === '') {
            return errorMsg;
        }
    },
    minLength(value, length, errorMsg) {
        if (value.length < length) {
            return errorMsg;
        }
    },
    isMobile(value, errorMsg) {
        if (!/(^1[3|5|8][0-9]{9}$)/.test(value)) {
            return errorMsg;
        }
    }
};

class Validator {
    constructor() {
        this.cache = [];
    }

    add(dom, rules) {
        let self = this;
        for (let i = 0, rule; rule = rules[i++]; ) {
            ((rule) => {
                let strategyArr = rule.strategy.split(':');
                let errorMsg = rule.errorMsg;
                self.cache.push(() => {
                    let strategy = strategyArr.shift();
                    strategyArr.unshift(dom.value);
                    strategyArr.push(errorMsg);
                    return strategies[ strategy ].apply(dom, strategyArr);
                })
            })(rule)
        }
    }

    start() {
        // 这个循环是如何停下来的？
        // validatorFunc = this.cache[i++] 语句的结果作为判断条件，
        // 当 this.cache 越界时，语句结果为 undefined 即 false，循环结束
        for (let i = 0, validatorFunc; validatorFunc = this.cache[i++]; ) {
            let errorMsg = validatorFunc();
            if (errorMsg) {
                return errorMsg;
            }
        }
    }
}
